package com.sgcc.isc.service.impl;

import com.sgcc.common.core.domain.R;
import com.sgcc.common.core.utils.DateUtils;
import com.sgcc.isc.domain.SysDistrict;
import com.sgcc.isc.service.ISysDistrictService;
import com.sgcc.isc.service.IscService;
import com.sgcc.isc.type.BizOrgRoleOfUserType;
import com.sgcc.isc.type.BizOrgType;
import com.sgcc.isc.type.ExtendType;
import com.sgcc.isc.type.UserType;
import com.sgcc.isc.ualogin.client.util.Md5encyptUtil;
import com.sgcc.system.api.*;
import com.sgcc.system.api.domain.SysRole;
import com.sgcc.system.api.domain.SysRoleDept;
import com.sgcc.system.api.domain.SysUser;
import org.apache.log4j.helpers.LogLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.jws.WebService;
import javax.xml.ws.Holder;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@SuppressWarnings("ALL")
@WebService(serviceName = "IscService", // 与接口中指定的name一致
targetNamespace = "http://www.sgcc.com/isc/service/", // 与接口中的命名空间一致,一般是接口的包名倒
endpointInterface = "com.sgcc.isc.service.IscService"// 接口地址
)
@Component
public class IscServiceImpl implements IscService{

	@Value("${isc.pwd}")
    private String pwd;


	@Autowired
	private RemoteDeptService remoteDeptService;
	@Autowired
	private RemoteMenuService remoteMenuService;
	@Autowired
	private RemotePostService remotePostService;
	@Autowired
	private RemoteUserService remoteUserService;
	@Autowired
	private RemoteRoleService remoteRoleService;

	@Autowired
	private RemoteRoleDeptService remoteRoleDeptService;
	@Autowired
    private ISysDistrictService sysDistrictService;


	//业务角色分组
	@Override
	@Transactional
	public void syncBizRoleGroup(String bizrolegroupID, String bizrolegroupNAME, String updateDATE, String isDELETED,
			List<ExtendType> _extends, Holder<String> result, Holder<String> time, Holder<String> description) {
		// TODO Auto-generated method stub
		System.out.println("业务角色分组");
	}
	//组织同步
	@Override
	@Transactional
	public void syncBizOrganization(List<BizOrgType> orgList, Holder<String> result, Holder<String> time,
			Holder<String> description) {
		// TODO Auto-generated method stub
//		LogLog.debug("开始同步组织机构");
		for (BizOrgType bizOrgType : orgList) {
			bizOrgType.getISDELETED();
			SysDistrict sysDistrict=sysDistrictService.selectSysDistrictById(bizOrgType.getBIZORGID());
			if(null==sysDistrict) {
				sysDistrict=new SysDistrict();
				sysDistrict.setDistrictId(bizOrgType.getBIZORGID());
				sysDistrict.setParentId(bizOrgType.getPARENTBIZORGID());
				sysDistrict.setDistrictName(bizOrgType.getBIZORGNAME());
				sysDistrictService.insertSysDistrict(sysDistrict);
			}else {
				sysDistrict.setDistrictId(bizOrgType.getBIZORGID());
				sysDistrict.setParentId(bizOrgType.getPARENTBIZORGID());
				sysDistrict.setDistrictName(bizOrgType.getBIZORGNAME());
				sysDistrictService.updateSysDistrict(sysDistrict);
			}
		}
//		LogLog.debug("组织同步结束");

	}
	//菜单(资源)同步
	@Override
	@Transactional
	public void syncFunction(String funcID, String funcNAME, String funcURL, String parentFUNCID, String funcINFO,
			String sortNO, String funcSTATUS, String isLEAF, String updateDATE, String isDELETED,
			List<ExtendType> _extends, Holder<String> result, Holder<String> time, Holder<String> description) {
		// TODO Auto-generated method stub
		System.out.println("菜单(资源)同步");
//		ObjectMapper objectMapper = new ObjectMapper();
//		AjaxResult res=remoteMenuService.getInfoIsc(funcID);
//		if(null==res.get("data")) {
//			SysMenu menu=new SysMenu();
//			menu.setMenuId(funcID);
//			menu.setMenuName(funcNAME);
//			menu.setComponent(funcURL);
//			menu.setParentId(parentFUNCID);
//			menu.setOrderNum(sortNO);
//			menu.setStatus(funcSTATUS);
//			menu.setVisible(isLEAF);
//			menu.setPerms(funcINFO);
//			remoteMenuService.addIsc(menu);
//		}else {
//			SysMenu menu=objectMapper.convertValue(res.get("data"),  SysMenu.class);
//
//			menu.setMenuId(funcID);
//			menu.setMenuName(funcNAME);
//			menu.setComponent(funcURL);
//			menu.setParentId(parentFUNCID);
//			menu.setOrderNum(sortNO);
//			menu.setStatus(funcSTATUS);
//			menu.setVisible(isLEAF);
//			menu.setPerms(funcINFO);
//			remoteMenuService.editIsc(menu);
//		}

	}
	//用户同步(U)
	@Override
	@Transactional
	public void syncUser(List<UserType> userList, Holder<String> result, Holder<String> time,
			Holder<String> description) {
		// TODO Auto-generated method stub
		for (UserType userType : userList) {

			R<SysUser> res=remoteUserService.getInfoISC(userType.getUSERID());
			if(null==res.getData()) {
				SysUser user=new SysUser();
				user.setUserId(userType.getUSERID());
				user.setUserName(userType.getLOGINNAME());
				user.setNickName(userType.getREALNAME());
				user.setStatus(userType.getUSERSTATUS());
				user.setDeptId(1==userType.getBIZORGID().size()?userType.getBIZORGID().get(0):"200");
				user.setPhonenumber(userType.getOFFICEPHONE());
				user.setSex(userType.getGENDER());
				user.setEmail(userType.getEMAIL());
				user.setDelFlag(userType.getISDELETED());
				user.setCreateBy("isc");
				user.setCreateTime(DateUtils.getNowDate());
				try {
					user.setPassword(Md5encyptUtil.getEncryptedPwd(pwd));
				} catch (NoSuchAlgorithmException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				remoteUserService.addIsc(user);
			}else {
				SysUser user=res.getData();

//				user.setUserId(userType.getUSERID());
				user.setUserName(userType.getLOGINNAME());
				user.setNickName(userType.getREALNAME());
				user.setStatus(userType.getUSERSTATUS());
				user.setDeptId(1==userType.getBIZORGID().size()?userType.getBIZORGID().get(0):"200");
				user.setPhonenumber(userType.getOFFICEPHONE());
				user.setSex(userType.getGENDER());
				user.setEmail(userType.getEMAIL());
				user.setDelFlag(userType.getISDELETED());
				user.setUpdateBy("isc");

				try {
					user.setPassword(Md5encyptUtil.getEncryptedPwd(pwd));
				} catch (NoSuchAlgorithmException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				user.setUpdateTime(DateUtils.getNowDate());
				remoteUserService.editIsc(user);
			}

		}
		System.out.println("用户同步(U)");

	}
	//业务角色同步(R)
	@Override
	@Transactional
	public void syncBizRole(String bizroleID, String bizroleNAME, String bizrolegroupID, String updateDATE,
			String isDELETED, List<ExtendType> _extends, Holder<String> result, Holder<String> time,
			Holder<String> description) {
		LogLog.debug("开始同步业务角色");
		R<SysRole> res=remoteRoleService.getInfoISC(bizroleID);
		if(200!=res.getCode()) {
			return;
		}
		if(null==res.getData()) {
			SysRole role=new SysRole();
			role.setRoleId(bizroleID);
			role.setRoleName(bizroleNAME);
			role.setRoleKey(bizroleNAME);
			role.setCreateBy("isc");
			role.setCreateTime(DateUtils.getNowDate());
			role.setDelFlag(isDELETED);
			role.setDataScope("4");
			role.setRoleSort("0");
			role.setStatus("0");
			role.setCreateBy("isc");
			role.setCreateTime(DateUtils.getNowDate());
			remoteRoleService.addISC(role);
		}else {
			SysRole role=res.getData();

			role.setRoleId(bizroleID);
			role.setRoleName(bizroleNAME);
			role.setRoleKey(bizroleNAME);
			role.setCreateBy("isc");
			role.setCreateTime(DateUtils.getNowDate());
			role.setDelFlag(isDELETED);
			role.setDataScope("4");
			role.setRoleSort("0");
			role.setStatus("0");
			role.setUpdateBy("isc");
			role.setUpdateTime(DateUtils.getNowDate());
			remoteRoleService.editISC(role);
		}
		LogLog.debug("同步业务角色结束");
	}

	@Override
	@Transactional
	public void syncDataSet(String datasetID, String datasetNAME, String datasetCODE, String datatypeID,
			String updateDATE, String isDELETED, List<ExtendType> _extends, Holder<String> result, Holder<String> time,
			Holder<String> description) {
		// TODO Auto-generated method stub
		System.out.println("syncDataSet");
	}
	//业务角色与权限同步(RW)
	@Override
	@Transactional
	public void syncResOfBizRole(String bizroleID, List<String> resID, String updateDATE, List<ExtendType> _extends,
			Holder<String> result, Holder<String> time, Holder<String> description) {
		// TODO Auto-generated method stub
		System.out.println("业务角色与权限同步(RW)");

	}
	//权限(功能)同步(W)
	@Override
	@Transactional
	public void syncResource(String resID, String resNAME, String resCODE, String funcID, String resINFO, String sortNO,
			String updateDATE, String isDELETED, List<ExtendType> _extends, Holder<String> result, Holder<String> time,
			Holder<String> description) {
		// TODO Auto-generated method stub
		System.out.println("权限(功能)同步(W)");

	}
	//组织角色同步(P)
	@Override
	@Transactional
	public void syncBizOrgRole(String bizorgroleID, String bizorgroleNAME, String bizroleID, String bizorgID,
			String updateDATE, String isDELETED, List<ExtendType> _extends, Holder<String> result, Holder<String> time,
			Holder<String> description) {
		R<SysRoleDept> res=remoteRoleDeptService.getInfo(bizorgroleID);
		if(null==res.getData()) {
			SysRoleDept post=new SysRoleDept();
			post.setId(bizorgroleID);
			post.setRoleId(bizroleID);
			post.setDeptId(bizorgID);
			remoteRoleDeptService.add(post);
		}else {
			SysRoleDept post=res.getData();
			post.setId(bizorgroleID);
			post.setRoleId(bizroleID);
			post.setDeptId(bizorgID);
			remoteRoleDeptService.edit(post);
		}
	}
	//同步业务组织角色授权（同时变更用户组织和角色）
	@Override
	@Transactional
	public void syncBizOrgRoleOfUser(List<BizOrgRoleOfUserType> orgRoleOfUserList, String userID, String updateDATE,
			List<ExtendType> _extends, Holder<String> result, Holder<String> time, Holder<String> description) {
		// TODO Auto-generated method stub
		R<SysUser> res=remoteUserService.getInfoISC(userID);
		if(null!=res.getData()) {
			SysUser user=res.getData();
			Set<String> ids=new HashSet<String>();
			for (BizOrgRoleOfUserType orgRole : orgRoleOfUserList) {
				SysRoleDept post=new SysRoleDept();
				post.setDeptId(orgRole.getBIZORGID());
				post.setId(orgRole.getBIZORGROLEID());
				R<SysRoleDept> resPost=remoteRoleDeptService.findDeptRole(post);
				if(null!=resPost.getData()){
					ids.add(resPost.getData().getRoleId());
				}
			}
			String roles="";
			for (String str : ids) {
				roles+=str+",";
			}
			if(roles.length()>0) {
				roles=roles.substring(0, roles.length()-1);
			}
			user.setRoleIds(roles.split(","));
			remoteUserService.editIsc(user);
		}
		System.out.println("同步业务组织角色授权（同时变更用户组织和角色）");

	}
	//业务角色与菜单关联同步（RF）
	@Override
	@Transactional
	public void syncFunctionOfOrgRole(String bizorgroleID, List<String> funcID, String updateDATE,
			List<ExtendType> _extends, Holder<String> result, Holder<String> time, Holder<String> description) {
		// TODO Auto-generated method stub
		System.out.println("业务角色与菜单关联同步（RF）");

	}

	@Override
	@Transactional
	public void syncDataSetOfOrgRole(String bizorgroleID, List<String> datasetID, String updateDATE,
			List<ExtendType> _extends, Holder<String> result, Holder<String> time, Holder<String> description) {
		// TODO Auto-generated method stub
		System.out.println("syncDataSetOfOrgRole");

	}

	@Override
	@Transactional
	public void syncResOfOrgRole(String bizorgroleID, List<String> resID, String updateDATE, List<ExtendType> _extends,
			Holder<String> result, Holder<String> time, Holder<String> description) {
		// TODO Auto-generated method stub
		System.out.println("syncResOfOrgRole");

	}

	@Override
	@Transactional
	public void syncDataType(String datatypeID, String datatypeNAME, String datatypeCODE, String updateDATE,
			String isDELETED, List<ExtendType> _extends, Holder<String> result, Holder<String> time,
			Holder<String> description) {
		// TODO Auto-generated method stub
		System.out.println("syncDataType");

	}

	@Override
	@Transactional
	public void syncFunctionOfBizRole(String bizroleID, List<String> funcID, String updateDATE,
			List<ExtendType> _extends, Holder<String> result, Holder<String> time, Holder<String> description) {
		// TODO Auto-generated method stub
//		System.out.println("开始同步角色菜单");
//		SysRole role=roleService.selectRoleById(bizroleID);
//		if(null!=role) {
//			String[] menu=new String[funcID.size()];
//			for (int i = 0; i < funcID.size(); i++) {
//				menu[i]=funcID.get(i);
//			}
//			role.setMenuIds(menu);
//			roleService.updateRole(role);
//		}
		System.out.println("角色菜单同步结束");

	}
	/**
	 *
	 */
	@Override
	@Transactional
	public void syncBizRoleOfUser(String userID, List<String> bizroleID, String updateDATE, List<ExtendType> _extends,
			Holder<String> result, Holder<String> time, Holder<String> description) {
		// TODO Auto-generated method stub
//		System.out.println("开始同步用户角色");
//		SysUser user=userService.selectUserById(userID);
//		if(null!=user) {
//			String[] role=new String[bizroleID.size()];
//			for (int i = 0; i < bizroleID.size(); i++) {
//				role[i]=bizroleID.get(i);
//			}
//			user.setRoleIds(role);
//			userService.updateUser(user);
//		}

		System.out.println("同步用户角色结束");
	}

}
